import requests
import hmac
import base64
import pprint
import json
import  datetime
from .okex_consts import *
from utils.custom_log import log_start
logger = log_start('client')

class OkexAPI(object):
    def __init__(self,config):
        self.url = API_URL
        self.passphrase = config['passphrase']
        self.api_key =config['api_key']		
        self.secret_key = config['secret_key']
  

    def get_timestamp(self):
        ret = requests.get(SERVER_TIMESTAMP_URL).json()['iso']
        # now = datetime.datetime.utcnow()
        # ret = now.isoformat("T", "milliseconds")+ "Z"
        return ret 
    
    def pre_hash(self,timestamp, method, request_path, body):
        return str(timestamp) + str.upper(method) + request_path + body
    
    def sign(self,message, secretKey):
        mac = hmac.new(bytes(secretKey, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')
        d = mac.digest()
        return base64.b64encode(d).decode()

    def get_header(self,api_key, sign, timestamp, passphrase):
        header = dict()
        header[CONTENT_TYPE] = APPLICATION_JSON
        header[OK_ACCESS_KEY] = api_key
        header[OK_ACCESS_SIGN] = sign
        header[OK_ACCESS_TIMESTAMP] = str(timestamp)
        header[OK_ACCESS_PASSPHRASE] = self.passphrase
        return header

    #     return {
    #         'OK-ACCESS-KEY': self.api_key,
    #         'OK-ACCESS-SIGN': self.signature(current_timestamp, method, request_path, data, self.secret_key),
    #         'OK-ACCESS-TIMESTAMP': current_timestamp,
    #         'OK-ACCESS-PASSPHRASE': self.passphrase,
    #         'Content-Type': 'application/json;charset=UTF-8',
    #         }

    
    def http_get(self,url,request_path):
        """
        通用get查询请求
        """
        timestamp = self.get_timestamp() # 获取时间戳
        method = 'GET'
        body = ''
        my_sign = self.sign(self.pre_hash(timestamp, method, request_path, str(body)), self.secret_key)  # 签名
        header = self.get_header(self.api_key, my_sign, timestamp, self.passphrase)  # 设置请求头
        response = requests.get(url,headers=header,timeout=15)
        print("[get]",url,'\n')
        return response

    def http_post(self,url,request_path,body):
        """
        通用post请求
        """
        body = json.dumps(body)
        timestamp = self.get_timestamp() # 获取时间戳
        method = 'POST'
        my_sign = self.sign(self.pre_hash(timestamp, method, request_path, str(body)), self.secret_key)  # 签名
        header = self.get_header(self.api_key, my_sign, timestamp, self.passphrase)  # 设置请求头
        
        x_simulated_trading = {'x-simulated-trading': "1"}
        header.update(x_simulated_trading)
        print("[post]",url,'\n')
        pprint.pprint(header)


        try:
            response = requests.post(url,data=body, headers=header,timeout=5)
            return response
        except Exception as e:
            # raise Exception(e)
            print(e,"error")

        
   
    
    def get_wallet(self):
        request_path = "/api/v5/account/balance?ccy=USDT"
        url = "{0}{1}".format(self.url,request_path)

        response = self.http_get(url,request_path)
        if response.status_code == 200:
            info = "*****账号总资产: {} USDT*****".format(int(float(response.json()['data'][0]['totalEq'])))
            logger.info(info)

    def currencies(self):
        request_path = "/api/v5/asset/currencies"
        url = "{0}{1}".format(self.url,request_path)

        response = self.http_get(url,request_path)
        if response.status_code == 200:
            return response

    
    def account_position_risk(self):
        request_path = "/api/v5/account/account-position-risk"
        url = "{0}{1}".format(self.url,request_path)

        resp = self.http_get(url,request_path)
        balData = resp['data'][0]['balData']
        posData = resp['data'][0]['posData']
        # pprint.pprint(balData)
        pprint.pprint(posData)
   
    def order(self,instId,tdMode,side,posSide,ordType,sz,px=None):
        """
        下单
        """
        request_path = "/api/v5/trade/order"
        url = "{0}{1}".format(self.url,request_path)
        
        body = {
            "instId":instId,
            "tdMode":tdMode,
            "side":side,
            "ordType":ordType,
            "posSide":posSide,
            "sz":sz
        }
      
        response = self.http_post(url,request_path,body)
        return response
    
    
    def leverage_info(self,instId,mgnMode):
        """
        查看当前购买是杠杆倍数
        """
        request_path= "/api/v5/account/leverage-info?instId={0}&mgnMode={1}".format(instId,mgnMode)
        url = "{0}{1}".format(self.url,request_path)
        resp = self.http_get(url,request_path)
        pprint.pprint(resp)

    
    def close_position(self,instId,mgnMode):
        request_path = "/api/v5/trade/close-position"
        url = "{0}{1}".format(self.url,request_path)
        body = {
            "instId":instId,
            "mgnMode":mgnMode
        }

        response = self.http_post(url,request_path,body)
        return response

        
        